// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*************************************************************************
 * @file SimplePublisher.cpp
 * This file contains the implementation of the publisher functions.
 *
 * This file was generated by the tool fastrtpsgen.
 */


#include "SimplePublisher.h"
#include "SimplePubSubType.h"

SimplePublisher::SimplePublisher() : mp_RTPSParticipant(NULL), mp_publisher(NULL) {}

SimplePublisher::~SimplePublisher() {}

bool SimplePublisher::init()
{
	// Create RTPSParticipant
	
	RTPSParticipantAttributes PParam;
	PParam.builtin.domainId = 80;
	PParam.name = "RTPSParticipant_publisher";  //You can put here the name you want
	mp_RTPSParticipant = RTPSDomain::createRTPSParticipant(PParam);
	if(mp_RTPSParticipant == NULL)
		return false;
	
	// Create Publisher
	
	PublisherAttributes Wparam;
	Wparam.topic.topicKind = NO_KEY;
	Wparam.topic.topicDataType = "SimpleStructPubSubType";  //This type MUST be registered
	Wparam.topic.topicName = "SimplePubSubTopic";
	mp_publisher = RTPSDomain::createPublisher(mp_RTPSParticipant,Wparam,(PublisherListener*)&m_listener);
	if(mp_publisher == NULL)
		return false;
	return true;
}

void SimplePublisher::PubListener::onPublicationMatched(MatchingInfo info)
{
	if (info.status == MATCHED_MATCHING)
	{
		n_matched++;
		cout << "Publisher matched" << endl;
	}
	else
	{
		n_matched--;
		cout << "Publisher unmatched" << endl;
	}
}

void SimplePublisher::run()
{
	while(m_listener.n_matched == 0)
	{
		eClock::my_sleep(250); // Sleep 250 ms
	}
	
	// Publication code
	
	SimpleStruct st;
	
	/* Initialize your structure here */
	
	mp_publisher->write(&st);
}
